{% load static %}
<!DOCTYPE html>
<html>
    <head>
    <title>django-websocket</title>
    <script src="{% static 'js/jquery-3.2.1.min.js' %}"></script>
    <script type="text/javascript">//<![CDATA[
        $(function () {
            $('#connect_websocket').click(function () {
                if (window.s) {
                    window.s.send("end")
                }
                /*创建socket连接*/
                var socket = new WebSocket("ws://" + window.location.host + "/echo");
                socket.onopen = function () {
                    console.log('WebSocket open');//成功连接上Websocket
                };
                socket.onmessage = function (e) {
                    console.log('message: ' + e.data);//打印出服务端返回过来的数据
                    $('#messagecontainer').prepend('<p>' + e.data + '</p>');
                };
                // Call onopen directly if socket is already open
                if (socket.readyState === WebSocket.OPEN) socket.onopen();
                window.s = socket;
                {#window.s.close()#}
            });
            $('#send_message').click(function () {
                //如果未连接到websocket
                if (!window.s) {
                    alert("websocket未连接.");
                } else {
                    window.s.send($('#message').val());//通过websocket发送数据
                }
            });
            $('#close_websocket').click(function () {
                if (window.s) {
                    window.s.send("end");
                    {#window.s.close(3001,'onClose');//关闭websocket#}
                    window.s.onclose = function (ev) {
                        console.log(ev);
                    };
                    console.log('websocket已关闭');
                }
            });

        });
        //]]></script>
    </head>
    <body>
    <br>
    <input type="text" id="message" value="Hello, World!"/>
    <button type="button" id="connect_websocket">连接 websocket</button>
    <button type="button" id="send_message">发送 message</button>
    <button type="button" id="close_websocket">关闭 websocket</button>
    <h1>Received Messages</h1>
    <div id="messagecontainer">

    </div>
    </body>
</html>